package com.huajx.tuopuda.client.udp.handler;

import com.huajx.core.Hboot;
import com.huajx.core.kit.AsyncHttpClientKit;
import com.huajx.core.kit.HttpKit;
import com.huajx.core.util.MessageKit;
import com.huajx.tuopuda.client.udp.*;
import com.huajx.tuopuda.client.udp.config.SchoolConfig;
import com.huajx.util.CharUtil;
import com.huajx.util.HexUtil;
import com.huajx.util.StrUtil;
import com.huajx.util.date.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: di-parent
 * @description:
 * @author: lisa 叶新华
 * @create: 2019-09-27 01:53
 */
public class ReadRunStatusHandler extends AbstractTuopudaHandler {
    private static final Logger logger = LoggerFactory.getLogger(ReadRunStatusHandler.class);
    public static Map<String, String> map = new ConcurrentHashMap<>();
    public static Map<String, String> allDataMap = new ConcurrentHashMap<>();
    private static final String POST_URL = SERVER_URL + "/di/tuopuda/updPersons/";
    public static int errorNum=0;
    public static int successNum=0;
    public static boolean onOff=true;
    private static ReadRunStatusHandler me;

    private SchoolConfig config;
    public ReadRunStatusHandler(){
    	config = Hboot.config(SchoolConfig.class);
    	
    }
    public static ReadRunStatusHandler me() {
        if (me == null) {
            me = new ReadRunStatusHandler();
        }
        return me;
    }

  /*  @Override
    public void send(String ip, int port, int sn) {
    	if(onOff && successNum==4){
      		 //重置机器版时间
              SetDatetimeHandler.me().send(ip, port, sn);
       	}
        try {
            TuopudaMessage message = send(ip, port, sn, 1);
            int records = message.getRecords();
            if(records <=0) {
                return;
            }
            //put(message);
            for (int i = 1; i <= records; i++) {
                TuopudaMessage temp = sendRead(ip, port, sn, i);
                put(temp);
            }
            ansyncPost();
            clear(ip, port, sn, records);
        } catch (TuopudaException e) {
            e.printStackTrace();
        }
    }*/
    
    public void send(String ip, int port, int sn){
    	int record=TuopudaClient.getRecordCount(sn);
        if(onOff && successNum==4){
       		 //重置机器版时间
           SetDatetimeHandler.me().send(ip, port, sn);
		 }
         try {
             TuopudaMessage message = send(ip, port, sn, 1);
             int records = message.getRecords();
             if(records <=0) {
                 return;
             }
             logger.info("读取数据集合大小:{},预读取数据的大小{}",records,record);
             int startRecord=record+1;
             for (int i = startRecord; i <= records; i++) {
            	 logger.info("{}板上的数据:正在读取数据行数：{}",sn,i);
            	 //logger.info("在循环中读取数据集合大小:{},预读取数据的大小{}",records,TuopudaClient.record);
            	 TuopudaMessage temp = sendRead(ip, port, sn, i);
            	 ReadWriteRecord.write(sn, i);
            	 TuopudaClient.setRecordCount(sn, i);
            	 record=i;
                 put(temp);
             }
             ansyncPost();
             if(record >= 10000){
            	 clear(ip, port, sn, record);
            	 record=0;
            	 TuopudaClient.setRecordCount(sn, record);
            	 ReadWriteRecord.write(sn, 0);
             }
         } catch (TuopudaException e) {
             e.printStackTrace();
         }catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		}
    }
    
    /**
     * 将信息发送到平台端口解析
     */
    //@Override
    /*public void send(String ip, int port, int sn) {
       StringBuffer buffer=new StringBuffer();
       String schoolId = config.getId();
	   if(onOff && successNum==4){
      		 //重置机器版时间
              SetDatetimeHandler.me().send(ip, port, sn);
       	}
        try {
            TuopudaMessage message = send(ip, port, sn, 1);
            int records = message.getRecords();
            if(records <=0) {
                return;
            }
            for (int i = 1; i <= records; i++) {
                String info = sendReadInfo(ip, port, sn, i);
                buffer.append(info).append(",");
            }
            long start = DateUtil.currentSeconds();
            AsyncHttpClientKit.post(SERVER_URL+"/di/tuopuda/updPersonsInfo/" + schoolId,  buffer.toString(), content -> logger.info("请求HTTP处理时长:{},{}", DateUtil.currentSeconds() - start, content));
            clear(ip, port, sn, records);
        } catch (TuopudaException e) {
            e.printStackTrace();
        }
    }*/
    private byte[] send(String ip, int port, int function, int sn, int count) throws TuopudaException {
        return sendAndReceive(ip, port, encode(sn, function, count));//发送
    }

    private TuopudaMessage send(String ip, int port, int sn, int pos) throws TuopudaException {
        byte[] responseMsg = send(ip, port, TuopudaDirect.D_1081, sn, pos);//发送
        return new TuopudaDecode().decode(responseMsg);
    }
    
    private TuopudaMessage sendRead(String ip, int port, int sn, int pos) throws TuopudaException {
        byte[] responseMsg = send(ip, port, TuopudaDirect.D_108d, sn, pos);//发送
        return new TuopudaDecode().decode(responseMsg);
    }
    
    private String sendReadInfo(String ip, int port, int sn, int pos) throws TuopudaException{
    	byte[] responseMsg = send(ip, port, TuopudaDirect.D_108d, sn, pos);//发送
    	return HexUtil.bytesToHex(responseMsg);
    }


    /**
     * 清除已上传考勤记录
     *
     * @param ip
     * @param port
     * @param sn
     * @param count
     */
    private void clear(String ip, int port, int sn, int count) {

        try {
            send(ip, port, TuopudaDirect.D_108e, sn, count);
            logger.info("SN: {} 清除已上传记录 {} 项", sn, count);
        } catch (TuopudaException e) {
            logger.info("SN: {} 清除失败 {} ", sn, count);
            e.printStackTrace();
        }

    }

    private void put(TuopudaMessage message) {
        String key = message.toKey();
        if (allDataMap.containsKey(key)) {
            return;
        }
        int cardId = message.getCarId();//学生八位卡号
        int direct = message.getDirect();//学生八位卡号
        int address = message.getAddress();//机器板地址
        String info = message.getInfo();//机器板地址
        String date = DateUtil.format(message.getDate(), "yyMMddHHmmss");//考勤时间
//        String keyDate = DateUtil.format(message.getDate(), "yyMMddHHmm");

        StringBuilder sb = new StringBuilder("{");
        appendJson(sb, "info", info, true);
        appendJson(sb, "deviceId", address, true);
        appendJson(sb, "cardId", cardId, true);
        appendJson(sb, "direct", direct, true);
        appendJson(sb, "date", date, false);
       

        sb.append("}");
        map.put(key, sb.toString());

        allDataMap.put(key, "");
        return;
    }

    private void appendJson(StringBuilder sb, String key, Object value, boolean append) {
        sb.append(CharUtil.DOUBLE_QUOTES).append(key).append(CharUtil.DOUBLE_QUOTES).append(CharUtil.COLON);
        sb.append(CharUtil.DOUBLE_QUOTES).append(value).append(CharUtil.DOUBLE_QUOTES);
        if (append) {
            sb.append(CharUtil.COMMA);
        }
    }

    private void ansyncPost() {
        if (map.isEmpty()) {
            return;
        }

        String schoolId = config.getId();
        StringBuilder sb = new StringBuilder();
        sb.append(CharUtil.BRACKET_START);
        boolean first = true;
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String value = entry.getValue();
            if (StrUtil.isBlank(value)) {
                continue;
            }
            if (first) {
                first = false;
            } else {
                sb.append(CharUtil.COMMA);
            }
            sb.append(value);
        }
        sb.append(CharUtil.BRACKET_END);
        logger.info("向平台端传输数据{}个！", map.size());
        try {
        	  // 处理卡点数据
             long start = DateUtil.currentSeconds();
        	 AsyncHttpClientKit.post(POST_URL + schoolId,  sb.toString(), content -> logger.info("请求HTTP处理时长:{},{}", DateUtil.currentSeconds() - start, content));
           // HttpKit.post(POST_URL + schoolId, sb.toString());
        } catch (Exception e) {
            logger.error("向平台端传输数据{}个,失败,平台端链接信息错误！", map.size());
        }

        map.clear();
    }

    private byte[] encode(int sn, int function, int pos) {
        return super.encode(sn, function, bytes -> TuopudaUtil.replaceBytes(bytes, pos, 5, 4));
    }

//    public static void main(String[] args) {
//        try {
//            new ReadRunStatusHandler().send(null, 6000, 38144, 1);
//        } catch (TuopudaException e) {
//            e.printStackTrace();
//        }
//    }
}
